﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;
using Uco.Models;
using System.Data;
using Uco.Infrastructure;

namespace Uco.Areas.Admin.Controllers
{
    [Authorize]
    public class TextComponentController : BaseAdminController
    {
        public ActionResult Index()
        {
            return View();
        }
        [GridAction]
        public ActionResult _AjaxIndex()
        {
            return View(new GridModel<TextComponent>
            {
                Data = SF.GetTextComponentsRepository().ToList()
            });
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult _AjaxDelete(int id)
        {
            List<TextComponent> l = SF.GetTextComponentsRepository();
            l.RemoveAll(r => r.ID == id);
            SF.SaveTextComponents(l);
            SF.CleanTextComponentsRepository();

            CleanCache.CleanOutputCache();

            return View(new GridModel<TextComponent>
            {
                Data = SF.GetTextComponentsRepository().ToList()
            });
        }

        public ActionResult Create()
        {
            return View(new TextComponent());
        }

        [HttpPost]
        public ActionResult Create(TextComponent tc)
        {
            if (ModelState.IsValid)
            {
                List<TextComponent> l = SF.GetTextComponentsRepository();
                if (l.Count == 0) tc.ID = 1;
                else tc.ID = l.Max(r => r.ID) + 1;
                l.Add(tc);
                SF.SaveTextComponents(l);
                SF.CleanTextComponentsRepository();

                CleanCache.CleanOutputCache();

                return RedirectToAction("Index");
            }
            return View(tc);
        }

        public ActionResult Edit(int ID)
        {
            List<TextComponent> l = SF.GetTextComponentsRepository();
            return View(l.First(r => r.ID == ID));
        }

        [HttpPost]
        public ActionResult Edit(int ID, TextComponent item)
        {
            if (ModelState.IsValid)
            {
                List<TextComponent> l = SF.GetTextComponentsRepository();
                l.RemoveAll(r => r.ID == ID);
                l.Add(item);
                SF.SaveTextComponents(l);
                SF.CleanTextComponentsRepository();

                CleanCache.CleanOutputCache();

                return RedirectToAction("Index");
            }
            return View(item);
        }
    }
}
